#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
FastAPI服务诊断工具
"""

import sys
import os
import traceback

def check_python_version():
    """检查Python版本"""
    print(f"Python版本: {sys.version}")
    if sys.version_info < (3, 7):
        print("❌ 警告: Python版本过低，建议使用Python 3.7+")
        return False
    else:
        print("✓ Python版本检查通过")
        return True

def check_working_directory():
    """检查工作目录"""
    cwd = os.getcwd()
    print(f"当前工作目录: {cwd}")
    
    required_files = [
        "rule_maker_app.py",
        "../config.py",
        "../common/rule_flatten_handle.py"
    ]
    
    missing_files = []
    for file_path in required_files:
        full_path = os.path.abspath(file_path)
        if os.path.exists(full_path):
            print(f"✓ 找到文件: {file_path}")
        else:
            print(f"❌ 缺少文件: {file_path}")
            missing_files.append(file_path)
    
    return len(missing_files) == 0

def check_database_connection():
    """检查数据库连接"""
    try:
        sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
        from config import create_db_engine
        
        engine = create_db_engine()
        print("✓ 数据库引擎创建成功")
        
        # 测试连接
        with engine.connect() as conn:
            result = conn.execute("SELECT 1 FROM DUAL")
            if result.fetchone():
                print("✓ 数据库连接测试成功")
                return True
    except Exception as e:
        print(f"❌ 数据库连接失败: {e}")
        return False

def check_app_import():
    """检查应用导入"""
    try:
        from rule_maker_app import app
        print("✓ FastAPI应用导入成功")
        return True
    except Exception as e:
        print(f"❌ FastAPI应用导入失败: {e}")
        traceback.print_exc()
        return False

def run_diagnosis():
    """运行完整诊断"""
    print("=" * 60)
    print("🔍 FastAPI服务诊断工具")
    print("=" * 60)
    
    checks = [
        ("Python版本", check_python_version),
        ("工作目录和文件", check_working_directory),
        ("数据库连接", check_database_connection),
        ("应用导入", check_app_import),
    ]
    
    results = []
    for name, check_func in checks:
        print(f"\n📋 检查 {name}...")
        try:
            result = check_func()
            results.append(result)
        except Exception as e:
            print(f"❌ 检查失败: {e}")
            results.append(False)
    
    print("\n" + "=" * 60)
    print("📊 诊断结果汇总")
    print("=" * 60)
    
    passed = sum(results)
    total = len(results)
    
    for i, (name, _) in enumerate(checks):
        status = "✓ 通过" if results[i] else "❌ 失败"
        print(f"{name}: {status}")
    
    print(f"\n总体状态: {passed}/{total} 项检查通过")
    
    if passed == total:
        print("🎉 所有检查通过！可以正常启动服务")
        return True
    else:
        print("⚠️  存在问题，请修复后重试")
        print("\n💡 建议:")
        if not results[0]:
            print("- 升级Python到3.7+版本")
        if not results[1]:
            print("- 确保在正确的目录运行脚本")
            print("- 检查必要文件是否存在")
        if not results[2]:
            print("- 检查数据库连接配置")
            print("- 确认Oracle数据库服务正在运行")
        if not results[3]:
            print("- 检查导入依赖是否正确安装")
            print("- 查看详细错误信息")
        return False

if __name__ == "__main__":
    success = run_diagnosis()
    sys.exit(0 if success else 1)